package org.hiucung.localmusicdemo.activity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import org.hiucung.localmusicdemo.adapter.QQMusicAdapter;
import org.hiucung.localmusicdemo.bean.LocalMusicBean;
import org.hiucung.localmusicdemo.helper.MediaPlayerHelper;
import org.hiucung.localmusicdemo.R;
import org.hiucung.localmusicdemo.adapter.SearchMusicAdapter;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SearchActivity extends AppCompatActivity {

    ArrayList<LocalMusicBean> localMusicBeans = new ArrayList<>();
    Button btSearch;
    EditText etSearch;
    RecyclerView searchRv;
    ImageView icon;
    TextView song,singer;
    int currnetPausePosition;
    int currnetPlayPosition;

    QQMusicAdapter qqMusicAdapter;
    MediaPlayerHelper mediaPlayerHelper;//媒体
    LinearLayoutManager layoutManager;//设置布局管理器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        OnClick();
        mediaPlayerHelper = MediaPlayerHelper.getInstance(SearchActivity.this);
        qqMusicAdapter = new QQMusicAdapter(R.layout.activity_search,localMusicBeans);

        ScaleInAnimationAdapter scaleInAnimationAdapter = new ScaleInAnimationAdapter(qqMusicAdapter);
        scaleInAnimationAdapter.setDuration(1000);
        scaleInAnimationAdapter.setInterpolator(new OvershootInterpolator());
        scaleInAnimationAdapter.setFirstOnly(false);
        searchRv.setAdapter(scaleInAnimationAdapter);

//        searchRv.setAdapter(musicAdapter);
        //设置布局管理器
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        searchRv.setLayoutManager(layoutManager);

        //设置每一项的点击事件
        setEventListener();
    }

    private void loadDataForBottomAction() {

        song.setText(localMusicBeans.get(currnetPlayPosition).getSong());
        singer.setText(localMusicBeans.get(currnetPlayPosition).getSinger());
        //通过glide获取专辑封面
        Glide.with(this).load(localMusicBeans.get(currnetPlayPosition).getAlbumUrl()).into(icon);
    }

    /***
     * 点击事件通过实现接口实现类
     */
    private void setEventListener() {
        qqMusicAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                currnetPlayPosition = position;//获取点击的position
                LocalMusicBean musicBean = localMusicBeans.get(currnetPlayPosition);//根据position获取歌曲列表中的歌曲
                //播放该歌曲
                mediaPlayerHelper.pause();
                mediaPlayerHelper.setPath(musicBean.getPath());
                playMusic();
                //匹配数据到底部播放操作栏
                loadDataForBottomAction();
            }
        });
    }

    /***
     * 播放音乐按钮的方法
     */
    private void playMusic() {
        if (!mediaPlayerHelper.isPlaying()) {
            mediaPlayerHelper.setOnMeidaPlayerHelperListener(new MediaPlayerHelper.OnMeidaPlayerHelperListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayerHelper.start();
                }

                @Override
                public void onCompletion(MediaPlayer mp) {
                    //默认单曲循环
                    mediaPlayerHelper.seekTo(0);
                    mediaPlayerHelper.start();
                }
            });

        }else {
            //当音乐暂停之后再继续播放时不需要监听是否异步加载完成
            mediaPlayerHelper.seekTo(currnetPausePosition);
            mediaPlayerHelper.start();

        }
    }

    private void OnClick() {
        btSearch.setOnClickListener(v -> {
            System.out.println("需要搜索的是：" + etSearch.getText());
            String etResult = etSearch.getText().toString();

            String musicApi = "https://c.y.qq.com/soso/fcgi-bin/client_search_cp?aggr=1&cr=1&flag_qc=0&p=1&n=20&w=";

            OkHttpClient okHttpClient = new OkHttpClient();
            Request.Builder builder = new Request.Builder();

            Request request = builder.get().url(musicApi + etResult).build();

            Call call = okHttpClient.newCall(request);

            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    //由于返回体中包含不需要的字符我们需要剔除 "callback" 和一对小括号()
                    String callback = result.replace("callback", "");
                    String left = trimFirstAndLastChar(callback, '(');
                    String right = trimFirstAndLastChar(left, ')');

                    JSONArray res_arr = null;
                    localMusicBeans.clear();
                    try {
                        res_arr = new JSONObject(right).getJSONObject("data").getJSONObject("song").getJSONArray("list");
                        for (int i = 0; i < res_arr.length(); i++) {
                            String sid = String.valueOf(i);
                            String song = res_arr.getJSONObject(i).getString("songname");
                            String singer = res_arr.getJSONObject(i).getJSONArray("singer").getJSONObject(0).getString("name");
                            String songmid = res_arr.getJSONObject(i).getString("songmid");
                            String musicUrl = getMusicUrl(songmid);

                            //遍历每一首歌的专辑封面url
                            String albumm = res_arr.getJSONObject(i).getString("albummid");
                            String albumPicture = getAlbumPicture(albumm);

                            LocalMusicBean musicBean = new LocalMusicBean(sid, song, singer, "", "", musicUrl,albumPicture);
                            localMusicBeans.add(musicBean);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    System.out.println(localMusicBeans);
                }
            });
            try {
                //让线程睡一睡，为了让列表能拿到数据
                Thread.sleep(1000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        qqMusicAdapter.notifyDataSetChanged();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }


        });}


    //获取音乐的url地址
    private String getMusicUrl(String songmid) throws JSONException, IOException {

        String host = "https://u.y.qq.com";
        String pathLeft = "/cgi-bin/musicu.fcg?g_tk=5381&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0&data=";
        String pathRight = "{\"req\":{\"module\":\"CDN.SrfCdnDispatchServer\",\"method\":\"GetCdnDispatch\",\"param\":{\"guid\":\"8348972662\",\"calltype\":0,\"userip\":\"\"}},\"req_0\":{\"module\":\"vkey.GetVkeyServer\",\"method\":\"CgiGetVkey\",\"param\":{\"guid\":\"8348972662\",\"songmid\":[\"";
        String pathRight2 = "\"],\"songtype\":[1],\"uin\":\"0\",\"loginflag\":1,\"platform\":\"20\"}},\"comm\":{\"uin\":0,\"format\":\"json\",\"ct\":24,\"cv\":0}}";

        //把字符串转成json，再对json进行转码
        JSONObject jsonObject = new JSONObject(pathRight+songmid+pathRight2);
        String req = getTaskCreateJsonReq(jsonObject);

        //把最终的请求地址合并
        String path = pathLeft+req;

//        System.out.println(path);

        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder builder = new Request.Builder();

        Request request  = builder.get().url( host+path ).build();

        Call call = okHttpClient.newCall(request);

        ArrayList<String> ip = new ArrayList<>();

        Response response = call.execute();
        String result = response.body().string();

        JSONArray ipArray = new JSONObject(result).getJSONObject("req").getJSONObject("data").getJSONArray("freeflowsip");

        //获取歌曲的purl
        String purl = new JSONObject(result).getJSONObject("req_0").getJSONObject("data")
                .getJSONArray("midurlinfo").getJSONObject(0).getString("purl");

        //为每一个ip拼装purl
        for (int i = 0; i < ipArray.length(); i++) {
            ip.add(ipArray.getString(i)+purl);
        }

//        System.out.println("歌曲有以下ip地址可选："+ip);
//        System.out.println("list数组大小为："+ip.size());

        return ip.get(0);
    }

    //封装专辑封面url
    public String getAlbumPicture(String album){
        return "https://y.gtimg.cn/music/photo_new/T002R300x300M000"+album+".jpg?max_age=2592000";
    }

    //对json进行URLEncoder转码
    public String getTaskCreateJsonReq(JSONObject json){

        StringBuffer req = new StringBuffer();
        try {
            String encode = URLEncoder.encode(json.toString(), "UTF-8");
            //req.append("?data=" +encode);
            req.append(encode);
        } catch (UnsupportedEncodingException e){
            //req.append("?data=");
            //System.out.println("TaskReqUtils.getTaskCreateReq [JSONObject]: " + json.toString());
        }

        //System.out.println("TaskReqUtils.getTaskCreateReq [JSONObject]: " + json.toString());

        return req.toString();
    }


    /**
     * 去除字符串首尾出现的某个字符.
     * @param source 源字符串.
     * @param element 需要去除的字符.
     * @return String.
     */
    public String trimFirstAndLastChar(String source,char element){
        boolean beginIndexFlag = true;
        boolean endIndexFlag = true;
        do{
            int beginIndex = source.indexOf(element) == 0 ? 1 : 0;
            int endIndex = source.lastIndexOf(element) + 1 == source.length() ? source.lastIndexOf(element) : source.length();
            source = source.substring(beginIndex, endIndex);
            beginIndexFlag = (source.indexOf(element) == 0);
            endIndexFlag = (source.lastIndexOf(element) + 1 == source.length());
        } while (beginIndexFlag || endIndexFlag);
        return source;
    }

    private void initView() {
        btSearch = findViewById(R.id.btnSearch);
        etSearch = findViewById(R.id.etSearch);
        searchRv = findViewById(R.id.rvSongList);
        song = findViewById(R.id.local_music_bottom_tv_song_Search);
        singer = findViewById(R.id.local_music_bottom_tv_singer_Search);
        icon = findViewById(R.id.local_music_bottom_iv_icon_Search);
    }

}
